//
// Created by benxb on 2021/12/8.
//

#include <gtest/gtest.h>
#include <storage/data_chunk_io.h>
#include "type/value.h"


TEST(ChunkIOTest, WriteTest) {
    benxdb::DataChunkIO chunk_io("test");
    benxdb::DataChunk chunk(benxdb::FLOAT);
    int count = 0;
    while (!chunk.IsFull()) {
        chunk.AppendRecord(benxdb::Value(benxdb::FLOAT, 1.02f));
        count++;
    }
    chunk_io.AppendDataChunk(&chunk);
    ASSERT_EQ(count, benxdb::RECORD_COUNT_PER_CHUNK);
    chunk_io.DeleteTableFile();
}

TEST(ChunkIOTest, SingleWriteReadTest) {
    benxdb::DataChunkIO chunk_io("test");
    benxdb::DataChunk chunk(benxdb::FLOAT);
    int count = 0;
    while (!chunk.IsFull()) {
        chunk.AppendRecord(benxdb::Value(benxdb::FLOAT, 1024.2320f));
        count++;
    }
    chunk_io.AppendDataChunk(&chunk);
    ASSERT_EQ(count, benxdb::RECORD_COUNT_PER_CHUNK);

    benxdb::DataChunk* rd = chunk_io.ReadDataChunk(0);
    ASSERT_NE(rd, nullptr);
    ASSERT_EQ(rd->GetValueSize(), 4);
    for (int i = 0; i < rd->GetChunkSize()/4; i++) {
        ASSERT_EQ(rd->QueryIndex(i).GetAs<float>(), 1024.2320f);
    }
    chunk_io.DeleteTableFile();
}

TEST(ChunkIOTest, ManyWriteReadTest) {
    benxdb::DataChunkIO chunk_io("test");
    benxdb::DataChunk chunk(benxdb::FLOAT);
    int count = 0;
    while (!chunk.IsFull()) {
        chunk.AppendRecord(benxdb::Value(benxdb::FLOAT, 1024.2320f));
        count++;
    }
    for (int i = 0; i < 116; i++) {
        chunk_io.AppendDataChunk(&chunk);
    }
    ASSERT_EQ(count, benxdb::RECORD_COUNT_PER_CHUNK);

    benxdb::DataChunk* rd = chunk_io.ReadDataChunk(24);
    ASSERT_NE(rd, nullptr);
    ASSERT_EQ(rd->GetValueSize(), 4);
    for (int i = 0; i < rd->GetChunkSize()/4; i++) {
        ASSERT_EQ(rd->QueryIndex(i).GetAs<float>(), 1024.2320f);
    }
    chunk_io.DeleteTableFile();
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc,argv);
    return RUN_ALL_TESTS();
}